package org.springframework.ai.tool.execution;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.lang.reflect.Type;

public final class DefaultToolCallResultConverter implements ToolCallResultConverter {

    private static final Logger logger = LoggerFactory.getLogger(DefaultToolCallResultConverter.class);

    @Override
    public String convert(@Nullable Object result, @Nullable Type returnType) {
        if (returnType == Void.TYPE) {
            logger.debug("The tool has no return type. Converting to conventional response.");
            return "Done";
        }
        else {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL);
                // Create an ObjectMapper instance and configure it to ignore null values.
                return objectMapper.writeValueAsString(result);
            } catch (IOException e) {
                logger.error("DefaultToolCallResultConverter.convert e:{}",e);
                return "Done";
            }
        }
    }

}